<?php

declare(strict_types=1);

namespace App\Core;

final class AccessLogger
{
    private static float $startTime;

    public static function start(): void
    {
        self::$startTime = microtime(true);
    }

    public static function log(string $method, string $uri, int $status): void
    {
        $duration = isset(self::$startTime) ? round((microtime(true) - self::$startTime) * 1000, 2) : 0;
        $ip = self::getClientIp();
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

        $root = defined('APP_ROOT') ? APP_ROOT : dirname(__DIR__, 2);
        $dir = $root . '/storage/logs';
        if (!is_dir($dir)) {
            @mkdir($dir, 0777, true);
        }
        $file = $dir . '/access.log';

        $line = sprintf(
            '[%s] %s %s %s %d %sms "%s"',
            date('Y-m-d H:i:s'),
            $ip,
            $method,
            $uri,
            $status,
            $duration,
            substr($userAgent, 0, 200)
        );

        @file_put_contents($file, $line . PHP_EOL, FILE_APPEND);
    }

    private static function getClientIp(): string
    {
        $headers = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP'];
        foreach ($headers as $header) {
            if (!empty($_SERVER[$header])) {
                $ips = explode(',', (string)$_SERVER[$header]);
                $ip = trim($ips[0]);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }
        return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    }
}
